from concurrent.futures.process import _ThreadWakeup
from datetime import datetime

from vnpy.trader.object import TradeData
from vnpy.trader.constant import Direction


class TradeResult:
    """配对后的完整开平交易"""

    def __init__(self, size: int) -> None:
        """构造函数"""
        self.size = size

        # 交易成本
        self.long_cost: float = 0
        self.short_cost: float = 0

        # 交易仓位
        self.long_volume: float = 0
        self.short_volume: float = 0
        self.net_volume: float = 0

        # 开平时点
        self.open_dt: datetime = None
        self.close_dt: datetime = None

        # 成交记录
        self.trades: list[TradeData] = []

        # 交易盈亏
        self.pnl: float = 0

    def update_trade(self, trade: TradeData) -> bool:
        """更新成交"""
        # 添加成交记录
        self.trades.append(trade)

        # 更新成交数量和成本
        trade_cost = trade.price * trade.volume * self.size

        if trade.direction == Direction.LONG:
            self.long_volume += trade.volume
            self.long_cost += trade_cost
        else:
            self.short_volume += trade.volume
            self.short_cost += trade_cost

        self.net_volume = self.long_volume - self.short_volume

        if not self.net_volume:
            self.calculate_result()
            return True
        else:
            return False

    def calculate_result(self) -> None:
        """计算盈亏"""
        # 卖出收到现金，买入付出现金
        self.pnl = self.short_cost - self.long_cost

        self.open_dt = self.trades[0].datetime
        self.close_dt = self.trades[-1].datetime


class ResultManager:
    """交易配对管理器"""

    def __init__(self, size: int) -> None:
        """构造函数"""
        self.size = size

        # 第一条开平交易
        self.result: TradeResult = TradeResult(self.size)

        # 开平交易列表
        self.results: list[TradeResult] = []

    def update_trade(self, trade: TradeData) -> None:
        """更新成交"""
        closed = self.result.update_trade(trade)

        # 如果完成平仓，则创建下一条开平交易
        if closed:
            self.results.append(self.result)
            self.result = TradeResult(self.size)

    def get_results(self) -> list[TradeResult]:
        """获取记录"""
        return self.results
